package com.woorigil.social.controller.api.socialshopping;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.woorigil.social.Context;
import com.woorigil.social.MenuCategory;
import com.woorigil.social.controller.BaseController;
import com.woorigil.social.controller.CookieUtils;
import com.woorigil.social.domain.deal.DealCondition;
import com.woorigil.social.domain.deal.DealDao;
import com.woorigil.social.domain.deal.DealService;
import com.woorigil.social.domain.deal.DealViewList;
import com.woorigil.social.domain.deal.MainDealService;
import com.woorigil.social.domain.deal.RecentQuery;
import com.woorigil.social.domain.deal.RecentQueryDao;
import com.woorigil.social.domain.searcher.QueryAnalyzer;

@Controller
public class Version1_0_ApiController extends BaseController {
	@Autowired DealDao dealDao;
	@Autowired RecentQueryDao recentQueryDao;
	@Autowired DealService dealService;
	@Autowired MainDealService mainDealService;
	@Autowired QueryAnalyzer queryAnalyser;

	@RequestMapping("/api/main")
	public ModelAndView main(DealCondition condition, HttpServletRequest request) throws UnsupportedEncodingException {
		if (condition.getType() == DealCondition.Type.FREE_DEAL) {
			condition.setFree(true);
		}
		condition.setCategoryIds(getSubCategoryIds());
		
		ModelAndView mav = new ModelAndView("");
		mav.addObject("totalDealCount", Context.getTotalDealCount());
		mav.addObject("lastUpdatedAt", Context.getLastUpdatedAt());
		mav.addObject("popularQueries", queryAnalyser.findQueries(20));
		mav.addObject("recentDealViewList", getRecentViewDeals(CookieUtils.getValue(request, "RECENT_VIEW_DEALS")));
		mav.addObject("recentQueries", getRecentQueries(CookieUtils.getValue(request, "RECENT_QUERIES")));
		mav.addObject("condition", condition);
		mav.addObject("mainDealViewList", mainDealService.findMainDeals(10));
		mav.addObject("searchDealViewList", dealService.search(condition));
		return mav;
	}
	
	@RequestMapping("/api/serviceInfo")
	public ModelAndView serviceInfo() {
		ModelAndView mav = new ModelAndView("");
		mav.addObject("totalDealCount", Context.getTotalDealCount());
		mav.addObject("lastUpdatedAt", Context.getLastUpdatedAt());
		mav.addObject("popularQueries", queryAnalyser.findQueries(20));
		mav.addObject("mainMenus", Context.getMainMenus());
		mav.addObject("mainDealViewList", mainDealService.findMainDeals(10));
		return mav;
	}
	
	@RequestMapping("/api/categories")
	public ModelAndView category() {
		ModelAndView mav = new ModelAndView("");
//		mav.addObject("categories", Context.getMainMenus());
		return mav;
	}
	
	@RequestMapping("/api/my/recentViewDeals")
	public ModelAndView recentDeals(String sid) {
		ModelAndView mav = new ModelAndView("");
		mav.addObject("recentDealViewList", dealService.fidnAllRecentlyViewed(sid, 0));
		return mav;
	}	
	
	@RequestMapping("/api/mainDeals")
	public ModelAndView mainDeals(HttpServletRequest request) throws UnsupportedEncodingException {
		ModelAndView mav = new ModelAndView("");
		mav.addObject("mainDealViewList", mainDealService.findMainDeals(10));
		return mav;
	}	


	@RequestMapping("/api/search")
	public ModelAndView search(DealCondition condition) {
		if (condition.getType() == DealCondition.Type.FREE_DEAL) {
			condition.setFree(true);
		}
		condition.setCategoryIds(getSubCategoryIds());
		
		if (StringUtils.isNotBlank(condition.getQuery())) {
			RecentQuery recentQuery = recentQueryDao.selectBySidAndQuery(condition.getSid(), condition.getQuery());
			if (recentQuery == null) {
				recentQueryDao.insert(new RecentQuery(condition.getSid(), condition.getQuery(), new Date()));
			} else {
				recentQuery.setInsertDate(new Date());
				recentQueryDao.updateByQuery(recentQuery);
			}
		}
		
		DealViewList dealViewList = dealService.search(condition);
		
		ModelAndView mav = new ModelAndView("");
		mav.addObject("searchDealViewList", dealViewList);
		mav.addObject("condition", condition);
		return mav;
	}
	
	@RequestMapping("/api/my/recentQueries")
	public ModelAndView recentQueries(String sid) {
		ModelAndView mav = new ModelAndView("");
		mav.addObject("recentQueries", recentQueryDao.search(sid));
		return mav;
	}
	
	@RequestMapping("/api/my/deleteQuery")
	public ModelAndView recentQueries(String sid, String query) {
		ModelAndView mav = new ModelAndView("");
		mav.addObject("count", recentQueryDao.deleteBySidAndQuery(sid, query));
		return mav;
	}	

	private DealViewList getRecentViewDeals(String recentView) {
		if (StringUtils.isBlank(recentView)) {
			return new DealViewList("", null);
		}
		String[] dealIds = StringUtils.split(recentView, ",");
		DealCondition condition = new DealCondition();
		for (String each : dealIds) {
			condition.addDealIds(NumberUtils.toInt(StringUtils.trim(each), 0));
		}
		return dealService.search(condition);
	}
	
	private List<String> getRecentQueries(String values) {
		List<String> results = new ArrayList<String>();
		if (StringUtils.isBlank(values)) {
			return new ArrayList<String>();
		}
		try {
			String[] tempArray = StringUtils.split(URLDecoder.decode(values, "UTF-8"), ",");
			if (tempArray != null) {
				for (String each : tempArray) {
					if (!results.contains(each)) {
						results.add(each);
					}
				}
			}
		} catch (Exception e) {
		}
		return results;
	}
}
